<?php
namespace app\common\model;
/**
 * 
 * 关键字模型
 */
class Tag extends BaseModel {

    protected $createTime = false;
    protected $updateTime = false;
    /**
     * 添加关键字，并判断是否存在
     *  @param $tags string
     *  @return $ids 所有记录的ID
     */
    public static function saveData($tags){
        $ids = [];
        $tagarr = explode(',' , $tags);
        foreach($tagarr as $v){
            $tag = trim($v);
            $exist = self::where('tag_name' , $v)->find();
            if(isset($exist['id']) && $exist['id'] > 0){
                $ids[] = $exist['id'];
            }else{
                $my = new self();
                $my->tag_name = $v;
                $my->save();
                $ids[] = $my->id;
            }
        }
        return $ids;
    }

    public static function getTags($doc_id , $model = 'doc'){
        $data = self::field('a.id,a.tag_name')
            ->alias('a')
            ->join('__ARTICLE_'.strtoupper($model).'_TAG__ b' , 'b.tag_id=a.id')
            ->where('b.article_'.$model.'_id' , $doc_id)
            ->select();
        $tags = [];
        foreach($data as $v){
            $tags[] = $v['tag_name'];
        }
        return implode(',' , $tags);
    }

}